# -*- coding: utf-8 -*-
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from database import TwitterUser
import os,datetime,fetch

LINK_PREFIX = "https://twitter.com/"
INIT_PASSWORD = "custompassword"

class RankHandler(webapp.RequestHandler):

    def get(self):
        try:    page = int(self.request.get("page"))
        except: page = 1
        if page < 1: page = 1
        
        template_values = {
            "users": getRank(page,50),
            "page": page,
            "first": page>1,
            "nextpage": page+1,
            "prepage": page-1,
            "link_prefix": LINK_PREFIX
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/rank.html')
        self.response.out.write(template.render(path, template_values))

class BrowseHandler(webapp.RequestHandler):

    def get(self):
        try:    page = int(self.request.get("page"))
        except: page = 1
        if page < 1: page = 1
        
        template_values = {
            "statuses": getBrowse(page,50),
            "page": page,
            "first": page>1,
            "nextpage": page+1,
            "prepage": page-1,
            "link_prefix": LINK_PREFIX
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/browse.html')
        self.response.out.write(template.render(path, template_values))
        

class ApiHandler(webapp.RequestHandler):

    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/apidoc.html')
        self.response.out.write(template.render(path, {}))
        
        
class InitHandler(webapp.RequestHandler):

    def get(self):
        self.response.out.write(u"""
          <html>
            <body>
            <form action="/init" method="post">
                <label>初始化密码:</label><input type="password" name="pw" />
                <label>种子用户:</label><input type="text" name="username" />
                <input type="submit" name="submit" value="确定" />
            <form>
            </body>
          </html>
        """)
    
    def post(self):
        if self.request.get("pw") == INIT_PASSWORD:
            if self.request.get("username"):
                fetch.init(self.request.get("username"))
            else:
                fetch.init("bang590")
            twitterUser = db.GqlQuery("SELECT * FROM TwitterUser")
            if twitterUser.count() > 11:
                self.response.out.write("初始化成功")
            else:
                self.response.out.write("初始化错误，请换个用户重试")
        else:
            self.response.out.write("密码错误")


def getRank(page, count = 20):
    
    try:
        query = TwitterUser.all()
        if count*(page-1) > 1000:
            offset = int((count*(page-1))/1000)*1000
            tempUser = db.GqlQuery("SELECT * FROM TwitterUser ORDER BY followers_count DESC LIMIT 999,1")
            for i in tempUser: followers_count = i.followers_count
            
            if (offset > 1000):
                offset2 = offset
                while offset2 <> 1000:
                    tempUser = db.GqlQuery("SELECT * FROM TwitterUser WHERE followers_count < :1 ORDER BY followers_count DESC LIMIT 999,1", followers_count)
                    for i in tempUser: followers_count = i.followers_count
                    offset2 -= 1000
    
            query.filter("followers_count <", followers_count)
            query.order("-followers_count")
            users = query.fetch(count, count*(page-1)-offset)
        else:
            query.order("-followers_count")
            users = query.fetch(count, count*(page-1))
    except:
        return []
    
    values = []
    number = count*(page-1)
    for user in users:
        number += 1
        values.append({
           "profile_img_url": user.profile_image_url,
           "screen_name": user.screen_name,
           "name": user.name,
           "description": user.description,
           "followers_count": user.followers_count,
           "friends_count": user.friends_count,
           "statuses_count": user.statuses_count,
           "text": user.text,
           "text_date": str(user.text_created_at)[0:10],
           "number": number
        })
    return values


def getBrowse(page, count = 20):
    try:
        query = TwitterUser.all()
        query.order("-text_created_at")
        statuses = query.fetch(count, count*(page-1))
    except:
        return []
    
    values = []
    for status in statuses:
        try:
            date = datetime.datetime.strptime(str(status.text_created_at), "%Y-%m-%d %X" )
            date = str(date + datetime.timedelta(hours=8))           
            values.append({
               "profile_img_url": status.profile_image_url,
               "screen_name": status.screen_name,
               "name": status.name,
               "text": status.text,
               "created_at": date,
               "id": status.text_id,
               "source": status.text_source
            })
        except: pass
    return values
        
    


def main():
    application = webapp.WSGIApplication([('/', RankHandler),('/rank', RankHandler),('/browse', BrowseHandler),('/api', ApiHandler),('/init', InitHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
